var util = require('../../utils/util.js');
var utilMd5 = require('../../utils/md5.js');
var app = getApp();
const Upyun = require('../../utils/upyun-wxapp-sdk');
const upyun = new Upyun({
  bucket: util.upyun_bucket,
  operator: util.upyun_opterator,
  getSignatureUrl: util.upyun_getSignUrl
});

Page({

  /**
   * 页面的初始数据
   */
  data: {
    util: util,
    screen_w: 320,

    minHeight: 0,

    uploadImg: [],

    photo_w: 0,
    photo_h: 0,

    serviceImages: [],

    configData: '',

    showVideo: false
  },

  cuid: '',
  token: "",

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    
    var that = this;
    app.LoginUserInfo(function(res) {
      if(res && res != '-1' && res != '-2'){
        console.log("登录用户信息：", res);
        that.cuid = res.uid;
        that.token = res.token;
        that.getAllUpladedVideos();
      }
    });
    var p_w = (app.screen_w - 30)
    this.setData({
      isIphone_x: app.isIphone_x,
      screen_w: app.screen_w,
      screen_h: app.screen_h,
      minHeight: app.screen_h - 40,
      photo_w: p_w,
      photo_h: p_w * 0.5625
    })

    app.getWxCheck(function(show) {
      that.setData({
        showVideo: show
      })
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  showUploadModal () {
    var that = this
    tt.showModal({
      title: '提示',
      content: '视频上传失败，请检查网络是否畅通',
      confirmText: "重试",
      complete: (res) => {
        if (res.confirm) {
          that.upGoodsloadImgs() 
        }
      }
    })
  },

  //上传商品图片  uploadIndex 上传下标
  upGoodsloadImgs: function() {
    tt.showLoading({
      title: '视频上传中。。。',
      mask: "true"
    });
    
    var photos = this.data.uploadImg;
    let isUploadFinish = true
    for (var photoi = 0; photoi < photos.length; photoi++) {
      var imgInfo = photos[photoi];
      if (!imgInfo.videoIsUpload) {
        //视频上传
        isUploadFinish = false
        if(imgInfo.videoFailCount < 3) {
          let videoUrl = '/' + util.upyun_imgRootName + '/' + this.cuid + '/video/' + imgInfo.uploadName;
          this.upyunUpload(imgInfo.path, videoUrl, 'v', photoi)
        } else {
          this.showUploadModal()
        }
        break;
      } else if (!imgInfo.coverIsUpload) {
        //封面图片上传
        isUploadFinish = false
        if (imgInfo.coverFailCount < 3) {
          let coverUrl = '/' + util.upyun_imgRootName + '/' + this.cuid + '/video/' + imgInfo.uploadCoverName;
          this.upyunUpload(imgInfo.cover, coverUrl, 'i', photoi)
        } else {
          this.showUploadModal()
        }
        break;
      }
    }
    if (isUploadFinish) {
      this.uploadFinish(photos);
    }
  },

  upyunUpload: function(imageSrc, upyunUrl, type, uploadIndex) {
    var that = this
    console.log("imageSrc = " + imageSrc)
    console.log("upyunUrl = " + upyunUrl)
    console.log("type = " + type)
    console.log("uploadIndex = " + uploadIndex)
    var photos = that.data.uploadImg

    upyun.upload({
      localPath: imageSrc,
      remotePath: upyunUrl,
      success: function(res) {
        console.log("上传视频结果：", res);
        var resImgInfo = JSON.parse(res.data);
          if(type == 'i') {
            //是上传封面图片
            photos[uploadIndex].cover = util.upyun_imgHost + resImgInfo.url;
            photos[uploadIndex].coverIsUpload = true
          } else {
            //是上传视频
            photos[uploadIndex].url = util.upyun_imgHost + resImgInfo.url;
            photos[uploadIndex].videoIsUpload = true
          }
          that.upGoodsloadImgs()
      },

      fail: function(errMsg) {
        console.log("视频上传失败：" + that.data.uploadImg, errMsg);
          if(type == 'i') {
            //是上传封面图片
            photos[uploadIndex].coverFailCount++
          } else {
            //是上传视频
            photos[uploadIndex].videoFailCount++
          }
          that.upGoodsloadImgs()
      }
    })
  },

  uploadFinish: function(imageInfos) {
    console.log("视频信息：", imageInfos);
    var videoArr = []
    var imageArr = []
    var durationArr = []
    imageInfos.forEach(function(m, i) {
      imageArr = imageArr.concat(m.cover ? m.cover : '')
      videoArr = videoArr.concat(m.url ? m.url : '')
      durationArr = durationArr.concat(m.duration)
    });
    var that = this;
    var privatekey = utilMd5.hexMD5(that.cuid + 'savevideos' + that.token);
    var params = {
      "ac": "savevideos",
      "uid": that.cuid,
      "privatekey": privatekey,
      "postuid": that.cuid,
      "images": JSON.stringify(imageArr),
      "videos": JSON.stringify(videoArr),
      "durations": JSON.stringify(durationArr)
    }
    console.log("保存视频参数：", params)
    //保存图片信息到服务器
    util.api_go({
      data: params,
      method: 'POST',
      success: function(responseData) {
        console.log("保存视频链接返回：", responseData);
        if (responseData.data.res) {
          that.getAllUpladedVideos(true);
        }
        tt.hideLoading();
      }
    });


  },

  //选择图片
  selectLocalImg: function() {
    var that = this;
    tt.chooseMedia({
      count: 1,
      mediaType: ['video'],
      sourceType: ['album'],
      success: function(res) {
        console.log("本地视频信息：", res);
        const tempFiles = res.tempFiles;
        var selImgs = [];
        for (var i = 0; i < tempFiles.length; i++) {
          if (tempFiles[i].duration <= 15) {
            var imgInfo = {};
            //视频本地链接
            let timeStamp = util.getImgOrVideoName()
            imgInfo.path = tempFiles[i].tempFilePath;
            let v_houzui = imgInfo.path.substring(imgInfo.path.lastIndexOf('.'), imgInfo.path.length)
            imgInfo.uploadName = 'v_' + timeStamp + '_' + i + v_houzui;
            imgInfo.duration = parseInt(tempFiles[i].duration)
            imgInfo.videoIsUpload = false //标记是否上传了视频
            imgInfo.videoFailCount = 0 //标记视频上传失败次数，最多尝试3次

            //视频封面图片本地链接
            if (tempFiles[i].thumbTempFilePath) {
              imgInfo.cover = tempFiles[i].thumbTempFilePath
              let cover_houzui = imgInfo.cover.substring(imgInfo.cover.lastIndexOf('.'), imgInfo.cover.length)
              console.log("视频后缀：" + v_houzui);
              imgInfo.uploadCoverName = 'c_' +  timeStamp + '_' + i + cover_houzui;
              imgInfo.coverIsUpload = false //标记是否上传了封面
              imgInfo.coverFailCount = 0 //标记封面上传失败次数，最多尝试3次
            } else {
              imgInfo.cover = "/images/defaultthumb.jpeg"
              imgInfo.uploadCoverName = "defaultthumb.jpeg"
              imgInfo.coverIsUpload = true //标记是否上传了封面
              imgInfo.coverFailCount = 3 //标记封面上传失败次数，最多尝试3次
            }
          
            console.log("上传的视频信息：", imgInfo);
            selImgs[i] = imgInfo;
          } else {
            //大于15s的视频不给上传
            tt.showModal({
              title: '提示',
              content: '请上传小于15秒的视频',
              showCancel: false
            })
          }  
        }
        selImgs = that.data.uploadImg.concat(selImgs)
        that.setData({
          uploadImg: selImgs
        })
        // that.upGoodsloadImgs();
      },

      fail: function({
        errMsg
      }) {
        console.log('chooseImage fail, err is', errMsg)
      }
    });
  },

  //获取该用户所有已上传的视频信息
  getAllUpladedVideos: function(reget = false) {
    var that = this;
    tt.showLoading({
      title: 'loading...',
      mask: "true"
    });
    app.getAllUpladedvideos(that.cuid, reget, function(res){
      if(res != 0 && res != -1) {
        that.setData({
          serviceImages: res,
          uploadImg: []
        })
      } else {
        that.setData({
          serviceImages: []
        })
      }
      tt.hideLoading();
    })
  },

  //删除图片动作
  deleteAction:function(e){
    console.log("删除视频确认：", e)
    var noticeStr = e.currentTarget.dataset.selids != undefined ? "此操作不可恢复，确定删除选中视频吗？" : "确定删除选中视频吗？"
    var that = this;
    tt.showModal({
      title: '提示',
      content: noticeStr,
      success:function(res){
        if(res.confirm){
          if (e.currentTarget.dataset.selindex != undefined) {
            let selIndex = e.currentTarget.dataset.selindex
            console.log("删除本地选择的视频：" + selIndex)
            let localImgArr = that.data.uploadImg
            localImgArr.splice(selIndex, 1);
            that.setData({
              uploadImg: localImgArr
            })
          } else if (e.currentTarget.dataset.selids != undefined) {
            let selIdArr = []
            selIdArr.push(e.currentTarget.dataset.selids)
            console.log("选中的服务器视频id：", selIdArr)
            that.deleteVideos(selIdArr);  
          }
        }
      }
    })
  },

  //删除图片 
  deleteVideos: function(idsArr) {
    var that = this;
    var privatekey = utilMd5.hexMD5(that.cuid + 'delvideos' + that.token);
    tt.showLoading({
      title: '',
      mask: true
    })
    //保存图片信息到服务器
    util.api_go({
      data: {
        "ac": "delvideos",
        "uid": that.cuid,
        "privatekey": privatekey,
        "postuid": that.cuid,
        "imgids": JSON.stringify(idsArr)
      },
      method: 'POST',
      success: function(responseData) {
        tt.hideLoading()
        console.log("删除图片返回：", responseData);
        if (responseData.data.res) {
          tt.showToast({
            title: "删除成功"
          })
          that.getAllUpladedVideos(true);
        } else {
          tt.showToast({
            title: responseData.data.msg
          })
        }
      }
    });
  },

  goAtherPage: function(e) {
    var url = e.currentTarget.dataset.link;
    tt.navigateTo({
      url: url
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

})